
const db = require("../db/index")
const moment = require("moment")
const formidable = require("formidable")
const path = require("path")
const fs = require("fs")

//总条数
const getTotalNum = (res, keyword) => {
    return new Promise((resolve, reject) => {
        //总数目
        let sql1 = `select count(*) as num from sp_goods where is_del="0"
            ${keyword && keyword !== "" ? "and goods_name like '%" + keyword + "%'" : ''}`
        db.query(sql1, (err, result) => {
            if (err) return res.sendErr(err)
            resolve(result[0].num)
        })
    })
}
//商品列表
const getGoodList = async (req, res) => {
    // console.log(Date.parse(new Date()) / 1000);
    console.log(req.query)
    //总数目
    let num = await getTotalNum(res, req.query.keyword)
    //分页
    let sql = `select goods_id,goods_name,goods_price,goods_weight,goods_state,add_time,goods_number,upd_time,
        hot_mumber ,is_promote,goods_introduce from sp_goods where is_del='0' ${req.query.keyword && req.query.keyword !== "" ? "and goods_name like '%" + req.query.keyword + "%'" : ''}
        order by add_time desc
        limit ${req.query.pageNum} offset ${(req.query.currentPage - 1) * (req.query.pageNum - 0)}`

    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        // if (result.length === 0) return res.sendErr("不存在商品信息")

        //将result的时间替换
        Object.keys(result).forEach((key, index) => {
            result[key].add_time = moment(result[key].add_time * 1000).format("YYYY-MM-DD:HH-MM-SS")
            result[key].upd_time = moment(result[key].upd_time * 1000).format("YYYY-MM-DD:HH-MM-SS")
        })
        //成功
        res.send({
            status: 200,
            message: "获取商品信息成功!",
            data: result,
            totalNum: num
        })
    })
}


//删除商品
const delGood = (req, res) => {
    console.log(req.body);
    let sql = "update sp_goods set is_del='1' where goods_id=?"
    db.query(sql, req.body.goods_id, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("删除商品失败!")
        res.send({
            status: 200,
            message: "删除商品成功!"
        })
    })
}

//类别数目（level0）
const getTotalLevel0Num = (req, res) => {
    let sql = `select cat_id,cat_name,cat_pid,cat_level,cat_deleted from 
                    sp_category where cat_deleted=0 and cat_level=0 `
    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.length === 0) return res.sendErr("找不到 0 级类别!")
        res.send({
            status: 200,
            message: "获取分类数目成功!",
            total: result.length
        })
    })
}
//商品类别（三类）
const getLevel1 = (req, res) => {
    let sql = `select cat_id,cat_name,cat_pid,cat_level,cat_deleted from 
                    sp_category where cat_deleted=0 and cat_level=1`
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            if (result.length === 0) return res.sendErr("找不到 1 级类别!")
            resolve(result)
        })
    })
}
const getLevel1_2 = (req, res, res_level1) => {
    let _sql = `select cat_id,cat_name,cat_pid,cat_level,cat_deleted from 
                    sp_category where cat_deleted=0 and cat_level=2 and cat_pid=`
    return new Promise((resolve, reject) => {
        //遍历level1
        Object.keys(res_level1).forEach((key, index) => {
            let sql = _sql + res_level1[key].cat_id
            //每个level找孩子
            // res_level1[key].children = []
            db.query(sql, (err, result) => {
                if (err) return res.sendErr(err)
                //1级没有2级是可以接受的
                // if (result.length === 0) return res.sendErr("找不到 2 级类别!")
                res_level1[key].children = result

                if (index === res_level1.length - 1) {
                    resolve(res_level1)
                }
            })
        });
    })
}
const getLevel0 = (req, res) => {
    let sql;
    if (JSON.stringify(req.query) === '{}') {
        sql = `select cat_id,cat_name,cat_pid,cat_level,cat_deleted from 
                    sp_category where cat_deleted=0 and cat_level=0`
    } else {
        let currentPage = req.query.currentPage
        let pageNum = req.query.pageNum
        sql = `select cat_id,cat_name,cat_pid,cat_level,cat_deleted from 
                        sp_category where cat_deleted=0 and cat_level=0 limit
                        ${(currentPage - 1) * (pageNum - 0)},${pageNum - 0}`
    }
    return new Promise((resolve, reject) => {
        db.query(sql, (err, result) => {
            if (err) return res.sendErr(err)
            if (result.length === 0) return res.sendErr("找不到 0 级类别!")
            resolve(result)
        })
    })
}
const getLevel0_1_2 = (res_level0, res_level1_2) => {
    return new Promise((resolve, reject) => {
        res_level0.forEach((item1, index1) => {
            item1.children = []
            res_level1_2.forEach((item2, index2) => {
                if (item2.cat_pid === item1.cat_id) {
                    item1.children.push(item2)
                }
                //最后
                if (index1 === res_level0.length - 1 && index2 === res_level1_2.length - 1) {
                    resolve(res_level0)
                }
            })
        })
    })
}
const getGoodCategory = async (req, res) => {
    let res_level1 = await getLevel1(req, res)
    let res_level1_2 = await getLevel1_2(req, res, res_level1)
    let res_level0 = await getLevel0(req, res)
    let res_level0_1_2 = await getLevel0_1_2(res_level0, res_level1_2)

    res.send({
        status: 200,
        message: "获取商品类别成功!",
        data: res_level0_1_2
    })
}

const getLevel0_1 = (res_level0, res_level1) => {
    return new Promise((resolve, reject) => {
        res_level0.forEach((item1, index1) => {
            item1.children = []
            res_level1.forEach((item2, index2) => {
                if (item2.cat_pid === item1.cat_id) {
                    item1.children.push(item2)
                }
                if (index1 === res_level0.length - 1 && index2 === res_level1.length - 1) {
                    resolve(res_level0)
                }
            })
        })
    })
}
//获取商品类别(两类)
const getGoodCateTwoLevel = async (req, res) => {
    let res_level0 = await getLevel0(req, res)
    let res_level1 = await getLevel1(req, res)
    let res_level0_1 = await getLevel0_1(res_level0, res_level1)

    res.send({
        status: 200,
        message: "商品类别(两类)获取成功",
        data: res_level0_1
    })
}

//获取属性 attribute
const getGoodAttribute = (req, res) => {
    console.log(req.query);
    let sql = `select attr_id,attr_name,cat_id,attr_sel,attr_write,attr_vals from sp_attribute where cat_id=${req.query.cat_id}`
    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        // if(result.length ===0) return res.sendErr("没有属性")
        //many + only
        let manyAttribute = result.filter(item => {
            return item.attr_sel === "many"
        })
        Object.keys(manyAttribute).forEach(key => {
            if (manyAttribute[key].attr_vals !== "") {
                manyAttribute[key].attr_vals = manyAttribute[key].attr_vals.split(",")
            }
        })
        let onlyAttribute = result.filter(item => {
            return item.attr_sel === "only"
        })
        // console.log(manyAttribute);
        res.send({
            status: 200,
            message: "获取商品属性成功!",
            data: {
                manyAttribute: manyAttribute,
                onlyAttribute: onlyAttribute
            }
        })
    })
}

//添加商品
const addGood = (req, res) => {
    var form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, '../coverImg') // 上传目录
    form.parse(req, function (error, fields, files) {
        if (error) return res.sendErr(error)
        // console.log("fields", fields);// fields 除了图片外的信息
        // console.log("files", files);  // files 图片信息

        // 上传了头像
        if (JSON.stringify(files) !== "{}") {
            // 文件重命名（保存文件）
            let originalFilename = files['goods_img'].originalFilename  //文件原始的名称 如01.jpg
            let extName = path.extname(originalFilename)    //.jpg
            let baseName = path.basename(originalFilename, extName)  //o1
            let newName = baseName + '-' + Date.now() + extName;
            let oldPath = files['goods_img'].filepath
            fs.rename(oldPath, path.join(__dirname, '../coverImg', `${newName}`), (err) => {
                if (err) {
                    console.log('重命名失败！');
                    return res.sendErr('上传失败(重命名失败！)')
                }
            })
            //图片
            var pics = "http://localhost:3006/api/" + newName
        }
        //商品信息
        const goodsInfo = {}
        goodsInfo.goods_name = JSON.parse(fields.goods_name)
        goodsInfo.goods_price = fields.goods_price - 0
        goodsInfo.goods_number = fields.goods_number - 0
        goodsInfo.goods_weight = fields.goods_weight - 0
        goodsInfo.cat_id = JSON.parse(fields.goods_cat)[2]
        goodsInfo.goods_introduce = fields.goods_introduce
        goodsInfo.add_time = Math.round(moment() / 1000)
        goodsInfo.upd_time = Math.round(moment() / 1000)
        goodsInfo.cat_one_id = JSON.parse(fields.goods_cat)[0]
        goodsInfo.cat_two_id = JSON.parse(fields.goods_cat)[1]
        goodsInfo.cat_three_id = JSON.parse(fields.goods_cat)[2]

        let sql = "insert into sp_goods set ?"
        let goodsAttr = []
        db.query(sql, goodsInfo, (err, result) => {
            if (err) {
                if (err.errno === 1062) return res.sendErr("名字已被使用!", 1063)
                return res.sendErr(err)
            }
            if (result.affectedRows !== 1) return res.sendErr("添加商品失败!")
            // console.log("#", result);

            if (pics) {
                //插入图片
                let sql2 = "insert into sp_goods_pics(goods_id,pics_big,pics_mid,pics_sma) values(?,?,?,?) "
                db.query(sql2, [result.insertId - 0, pics, pics, pics], (err, result) => {
                    if (err) return res.sendErr(err)
                    if (result.affectedRows !== 1) return res.sendErr("商品图片插入失败")
                })
            }

            let mantIsNull = true;
            for (let val of Object.keys(JSON.parse(fields.selectedManyAttribute))) {
                if (val.length != 0) {
                    mantIsNull = false
                    break
                }
            }
            // console.log("mantIsNull=", mantIsNull);

            //没属性参数直接添加  ====
            if (mantIsNull && fields.selectedOnlyAttribute === "[]") {
                return res.send({
                    status: 200,
                    message: "添加成功!",
                })
            }

            //商品属性(需要上面得到的id 通过select max得到)
            // fields.selectedManyAttribute !== "[]" &&
            // goodsAttr.push({
            //     "goods_id": result.insertId - 0,
            //     "attr_id": fields.manyAttribute_id,
            //     "attr_value": JSON.parse(fields.selectedManyAttribute).join(" ")
            // })
            Object.keys(JSON.parse(fields.selectedManyAttribute)).forEach(key => {
                JSON.parse(fields.selectedManyAttribute)[key].length !== 0 &&
                    goodsAttr.push({
                        "goods_id": result.insertId - 0,
                        "attr_id": key,
                        "attr_value": JSON.parse(fields.selectedManyAttribute)[key].join(" ")
                    })
            })

            // fields.selectedOnlyAttribute !== "[]" &&
            JSON.parse(fields.selectedOnlyAttribute).forEach(obj => {
                goodsAttr.push({
                    "goods_id": result.insertId - 0,
                    "attr_id": obj.attr_id,
                    "attr_value": obj.attr_vals
                })
            })


            //插入attr
            let sql3 = "insert into sp_goods_attr set ?"
            goodsAttr.forEach((item, index) => {
                db.query(sql3, item, (err, result) => {
                    if (err) return res.sendErr(err)
                    if (result.affectedRows !== 1) return res.sendErr("添加商品属性失败!")
                })

                if (index === goodsAttr.length - 1) {
                    res.send({
                        status: 200,
                        message: "添加成功!",
                    })
                }
            })
        })
    })
}

//更改类别名称
const editCategoryName = (req, res) => {
    let sql = "update sp_category set cat_name = ? where cat_id = ?"
    db.query(sql, [req.body.cat_name, req.body.cat_id], (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("更改商品名称失败")

        res.send({
            status: 200,
            message: "更改商品名称成功",
        })
    })
}

//删除类别
const delGoodCategory = (req, res) => {
    console.log(req.body);
    let sql = "update sp_category set cat_deleted = 1 where cat_id = ?"
    db.query(sql, req.body.cat_id, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.affectedRows !== 1) return res.sendErr("删除商品名称失败")

        res.send({
            status: 200,
            message: "删除商品类别成功",
        })
    })
}

//添加类别
const addGoodCategory = (req, res) => {
    //cat_id cat_name 级别为长度
    let sql = "insert into sp_category set ?"
    db.query(sql, req.body, (err, result) => {
        if (err) return res.sendErr(err)
        if (result.length !== 1) return res.sendErr("添加商品分类失败！")
        res.send({
            status: 200,
            message: "添加商品分类成功!"
        })
    })
}


module.exports = {
    getGoodList,
    delGood,
    getGoodCategory,
    getGoodCateTwoLevel,
    getGoodAttribute,
    addGood,
    getTotalLevel0Num,
    editCategoryName,
    delGoodCategory,
    addGoodCategory
}